<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户控制器
 * @author Calvin
 *
 */
class User extends MY_Controller{
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('user_model');
		$this->load->service('user_info_service');
		$this->load->service('register_service');
		$this->load->service('user_verify_service');
		$this->load->library("form_validation");
		$this->config->load("form_validation");
	}
	
	//载入视图
	/*public function user_info(){
		$row = $this->login_service->get_user_info();
		$this->smarty->assign('title', '用户资料');
		$this->smarty->view('user/user_info.tpl', $row);
	}*/
	
	//载入修改资料视图
	public function user_info()
	{
		$row = $this->user_info_service->get_user_info($this->uid,"image,nickname,company_name,mobile,n_mobile,email,n_email");
		if(empty($row))
		{
			$this->login_service->logout();
		}
		$this->login_service->refresh_user_info($row);
		$this->template->assign('title', '修改个人资料');
		$row['email']=Common::hide_email($row['email']);
		$row['mobile']=Common::hide_tel($row['mobile']);
		$this->template->view('user/user_info.tpl', $row);
	}
	
	//保存信息表单处理
	public function update_user_info()
	{
		if($this->form_validation->run('update_user_info')==FALSE)
		{
			return Common::ajax_return(1003);
		}
		$data = array(
				'nickname'     => rtrim($this->input->post('nickname', TRUE)),
				'company_name' => rtrim($this->input->post('company_name', TRUE)),
				'image' => trim($this->input->post('image', TRUE))
				);
		$old_image = $this->login_service->get_user_info("image");
		$old_image_path = $this->input->server("DOCUMENT_ROOT").$old_image;
		//$exclude_image_path = $this->input->server("DOCUMENT_ROOT").$data['image'];
		//Common::console($old_image_path);
		if($data['image']!=$old_image && file_exists($old_image_path))
		{
			$this->user_info_service->clear_face_tmp(dirname($old_image_path),array($data['image'],$old_image));
		}
		//检查手机
		$n_mobile = trim($this->input->post('n_mobile',TRUE));
		if(!empty($n_mobile) && $this->register_service->check_phone_exists($n_mobile))
		{
			return Common::ajax_return(5009);
		}
		else if(!empty($n_mobile))
		{
			$data['n_mobile'] = $n_mobile;
		}

		//检查邮件
		$n_email = trim($this->input->post('n_email',TRUE));
		if(!empty($n_email) && $this->register_service->check_email_exists($n_email))
		{
			return Common::ajax_return(5001);
		}
		else if(!empty($n_email))
		{
			$data['n_email'] = $n_email;
		}

		$this->user_info_service->update_user_info($this->uid,$data);
		$this->login_service->reload_user_info();
		return Common::ajax_return(0);
	}
	
	//上传头像
	public function upload_img(){
		$image = $this->login_service->get_user_info("image");
		$upload = $this->user_info_service->upload_face($this->uid,$image);
		if($upload===FALSE)
		{
			Common::ajax_return($this->user_info_service);
		}
		else
		{
			Common::ajax_return(0,NULL,$upload,FALSE);
		}
		/*$default_path = $this->config->item("default_upload_path");
		$default_url = $this->config->item("default_upload_url");
		$max_size = $this->config->item("default_upload_img_max_size");
		$dir = $default_path.'user/image/';
		$url = $default_url.'user/image/';
		Common::create_folder($dir);
		$config['upload_path'] = $dir;
		$config['allowed_types'] = 'jpg|jpeg|png|gif';
		$config['max_size'] = $max_size;
		$config['file_name']  = sha1($this->uemail . mt_rand(0, 99) . time());
		$this->load->library('upload', $config);
		
		$field_name = 'upload_file';
		$return_data = array();
		if(!$this->upload->do_upload($field_name)){
			return Common::ajax_return(1010,$this->upload->display_errors('',''));
		} else {
			$file_data = array('upload_data' => $this->upload->data(), 'error' => 0);
			$return_data['img'] = $url.$file_data['upload_data']['file_name'];
			$old_image = $this->login_service->get_user_info("image");
			if($old_image){
				$path = $old_image;
				if(file_exists($path)){
					unlink($path);//删除旧的头像
				}
			}
			//$this->user_model->update($this->uid, $data);
			//echo json_encode($return_data);
			return Common::ajax_return(0,NULL,$return_data,FALSE);
		}*/
	}
	
	//载入修改密码视图
	public function update_pwd(){
		$data = array(
				'title' => '修改密码'
		);
		$this->template->view('user/update_pwd.tpl', $data);
	}
	
	//判断旧密码是否正确
	public function old_password_check(){
		$old_pwd = md5($this->input->post('old_password'));
		$pwd = $this->login_service->get_user_info("password");
		if($old_pwd != $pwd){
			$this->form_validation->set_message('old_password_check', '您的旧密码不正确');
			return false;
		}
		return true;
	}
	
	//修改密码表单处理
	public function do_update_pwd(){
		$this->form_validation->set_rules('old_password', '', 'required');
		$this->form_validation->set_rules('new_password', '', 'required');
		if(!$this->form_validation->run())
		{
			return Common::ajax_return(1003);
		}
		$old_pwd = md5($this->input->post('old_password'));
		$pwd = $this->login_service->get_user_info("password");
		if($old_pwd != $pwd){
			return Common::ajax_return(5013);
		}
		//更新数据库
		$data = array(
				'password'	=> md5($this->input->post('new_password'))
		);
		if($this->user_info_service->update_user_info($this->uid, $data))
		{
			//$this->register_service->logout();
			$this->login_service->reload_user_info();
			return Common::ajax_return(0,NULL,array("redirect"=>"/user/update_pwd_success"),FALSE);
		}
		else
		{
			return Common::ajax_return($this->user_info_service);
		}
	
	}

	public function update_pwd_success()
	{
		$data=array(
			"title"=>"密码修改成功",
			"type" =>"success",
			"msg" =>"你的密码已经修改成功",
			"url" =>"/files",
			"time"=>5
		);
		$this->template->view("common/message.tpl",$data);
	}
	
	public function get_space()
	{
		//是否格式化
		$type = (int)$this->input->get("type");
		if (empty($type)) {
			$ret = $this->user_info_service->get_format_space($this->uid);
		} else {
			$ret = $this->user_info_service->get_space($this->uid);
		}

		//common::prf_json ( TRUE, $ret );
		if($ret===FALSE)
		{
			Common::ajax_return($this->user_info_service);
		}
		else
		{
			Common::ajax_return(0,NULL,array("data"=>$ret),FALSE);
		}
	}

	private function check_old_phone()
	{
		//检查是否已经有绑定的手机
		if($this->login_service->get_user_info("mobile")=="")
		{
			show_404();
		}
	}

	public function valid_phone()
	{
		$mobile = $this->login_service->get_user_info("n_mobile");
		$sms_code_len=$this->config->item("sms_verify_code_length","user_common");
		if(empty($mobile))
		{
			show_404();
		}
		$data = array(
			'title' => '验证手机号码',
			'mobile'=>$mobile,
			'sms_code_len'=>$sms_code_len
		);
		$this->template->view('user/valid_phone.tpl', $data);
	}

	public function do_valid_phone()
	{
		$mobile = $this->input->post("mobile",TRUE);
		$code = $this->input->post("code",TRUE);
		if(empty($mobile) || empty($code))
		{
			return Common::ajax_return(1003);
		}
		$check = $this->user_verify_service->check_sms_code($code,$mobile,User_verify_service::PROCESS_VALID_PHONE,FALSE);
		if($check===FALSE)
		{
			return Common::ajax_return($this->user_verify_service);
		}
		else
		{
			$save = $this->user_info_service->update_user_info($this->uid,array("mobile"=>$mobile,"n_mobile"=>""));
			if($this->login_service->is_login())
			{
				$this->login_service->reload_user_info();
			}
			if(!$save)
			{
				return Common::ajax_return($this->user_info_service);
			}
			return Common::ajax_return(0,NULL,array("redirect"=>"/user/valid_phone_success"),FALSE);
		}
	}

	public function valid_phone_success()
	{
		$data=array(
			"title"=>"手机号码绑定成功",
			"type" =>"success",
			"msg" =>"你的手机号码已经绑定成功",
			"url" =>"/user/user_info",
			"time"=>5
		);
		$this->template->view("common/message.tpl",$data);
	}

	/**
	 * 发送验证手机号码短信
	 */
	public function send_valid_sms()
	{
		$this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$mobile = $this->input->post("mobile",TRUE);
			$check = $this->register_service->check_phone_exists($mobile);
			if($check)
			{
				return Common::ajax_return(5009);
			}
			$send = $this->user_verify_service->send_sms($mobile,User_verify_service::PROCESS_VALID_PHONE);
			if($send === FALSE)
			{
				return Common::ajax_return($this->user_verify_service);
			}
			return Common::ajax_return();
		}
	}

	public function new_phone()
	{
		$this->check_old_phone();
		$sms_code_len=$this->config->item("sms_verify_code_length","user_common");
		$data = array(
			'title' => '修改手机号码',
			"sms_code_len"=>	$sms_code_len
		);
		$this->template->view('user/new_phone.tpl', $data);
	}

	public function send_sms()
	{
		$this->check_old_phone();
		$this->form_validation->set_rules('mobile','', 'required|valid_mobile_phone');
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$mobile = $this->input->post("mobile",TRUE);
			$check = $this->register_service->check_phone_exists($mobile);
			if($check)
			{
				return Common::ajax_return(5009);
			}
			$send = $this->user_verify_service->send_sms($mobile,User_verify_service::PROCESS_MODIFY_PHONE,$this->uid,TRUE);
			if($send === FALSE)
			{
				return Common::ajax_return($this->user_verify_service);
			}
			return Common::ajax_return();
		}
	}

	public function check_phone()
	{
		$this->form_validation->set_rules('mobile', '', 'required|valid_mobile_phone');
		if(!$this->form_validation->run())
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$phone = $this->input->post("mobile",TRUE);
			if($this->login_service->get_user_info("mobile")==$phone)
			{
				return Common::ajax_return(5011);
			}

			$check = $this->register_service->check_phone_exists($phone,$this->uid);
			$ignore = $this->input->post("ignore",TRUE);
			if($check)
			{
				return Common::ajax_return(5009);
			}
			if(empty($ignore))
			{
				$can_send = $this->user_verify_service->can_send_sms($phone,User_verify_service::PROCESS_MODIFY_PHONE);
				if($can_send===FALSE)
				{
					$err_code =$this->user_verify_service->get_error("code");
					if($err_code==6003||$err_code==6004)
					{
						$error = $this->user_verify_service->get_error();
						return Common::ajax_return(0,$error['msg'],$error['info']);
					}
					else
					{
						return Common::ajax_return($this->user_verify_service);
					}
				}
			}
			return Common::ajax_return();
		}
	}

	public function save_new_phone()
	{
		$mobile = $this->input->post("mobile",TRUE);
		$code = $this->input->post("code",TRUE);
		if(empty($mobile) || empty($code))
		{
			return Common::ajax_return(1003);
		}
		$check = $this->user_verify_service->check_sms_code($code,$mobile,User_verify_service::PROCESS_MODIFY_PHONE,FALSE);
		if($check===FALSE)
		{
			return Common::ajax_return($this->user_verify_service);
		}
		else
		{
			$save = $this->user_info_service->update_user_info($this->uid,array("mobile"=>$mobile));
			if($this->login_service->is_login())
			{
				$this->login_service->reload_user_info();
			}
			if(!$save)
			{
				return Common::ajax_return($this->user_info_service);
			}
			return Common::ajax_return(0,NULL,array("redirect"=>"/user/save_new_phone_success"),FALSE);
		}
	}

	public function save_new_phone_success()
	{
		$data=array(
			"title"=>"手机号码修改成功",
			"type" =>"success",
			"msg" =>"你的新手机号码已经绑定成功",
			"url" =>"/user/user_info",
			"time"=>5
		);
		$this->template->view("common/message.tpl",$data);
	}



	private function check_old_email()
	{
		//检查是否已经有绑定的email
		if($this->login_service->get_user_info("email")=="")
		{
			show_404();
		}
	}

	public function send_valid_email()
	{
		if($this->login_service->get_user_info("n_email")=="")
		{
			show_404();
		}
		$this->form_validation->set_rules('email','', 'required|valid_email');
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$email = $this->input->post("email",TRUE);
			$check = $this->register_service->check_email_exists($email);
			if($check)
			{
				return Common::ajax_return(5001);
			}
			$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_VALID_EMAIL,"email_callback/valid_user_email",$this->uid);
			if($send === FALSE)
			{
				return Common::ajax_return($this->user_verify_service);
			}
			return Common::ajax_return(0,NULL,array("redirect"=>"/user/send_valid_email_success/".urlencode($email)),FALSE);
		}
	}

	public function send_valid_email_success($email="")
	{
		$email = !empty($email)?$email:$this->input->get_post("email");
		if(empty($email))
		{
			show_404();
		}
		$email = urldecode($email);
		$to_email_url = Common::get_email_url($email);
		$this->template->assign('email', $email);
		$this->template->assign('to_email_url', $to_email_url);
		$this->template->assign('title', '验证邮箱');
		$this->template->assign('url', '/user/send_valid_email');
		$this->template->view('user/send_email_success.tpl');
	}

	/*public function do_valid_email($code="")
	{
		if(empty($code))
		{
			show_404();
		}
		$result = $this->user_verify_service->check_email_verify_code($code,"",User_verify_service::PROCESS_VALID_EMAIL,TRUE,TRUE);
		if($result===false)
		{
			$data = array(
				'title' => '验证邮箱',
				'model' => 'user'
			);
			$this->smarty->view('user/tips.tpl',$data);
			return false;
		}
		else
		{
			$this->user_info_service->update_user_info($result['uid'],array("email"=>$result['receiver'],"n_email"=>""));
			if($this->login_service->is_login())
			{
				$this->login_service->reload_user_info();
			}
			$data=array(
				"title"=>"邮箱验证成功",
				"type" =>"success",
				"msg" =>"你的邮箱已经绑定成功",
				"url" =>"/user/user_info",
				"time"=>5
			);
			$this->smarty->view("common/message.tpl",$data);
		}
	}*/

	public function new_email()
	{
		$this->check_old_email();
		$data = array(
			'title' => '修改邮箱'
		);
		$this->template->view('user/new_email.tpl', $data);
	}



	public function send_new_email()
	{
		$this->check_old_email();
		$this->form_validation->set_rules('email','', 'required|valid_email');
		if ($this->form_validation->run() == FALSE)
		{
			return Common::ajax_return(1003);
		}
		else
		{
			$email = $this->input->post("email",TRUE);

			if($this->login_service->get_user_info("email")==$email)
			{
				return Common::ajax_return(5012);
			}

			$check = $this->register_service->check_email_exists($email);
			if($check)
			{
				return Common::ajax_return(5001);
			}
			$send = $this->user_verify_service->send_email($email,User_verify_service::PROCESS_MODIFY_EMAIL,"email_callback/valid_new_email",$this->uid,TRUE);
			if($send === FALSE)
			{
				return Common::ajax_return($this->user_verify_service);
			}
			return Common::ajax_return(0,NULL,array("redirect"=>"/user/send_new_email_success/".urlencode($email)),FALSE);
		}
	}

	public function send_new_email_success($email="")
	{
		$email = !empty($email)?$email:$this->input->get_post("email");
		if(empty($email))
		{
			show_404();
		}
		$email = urldecode($email);
		$to_email_url = Common::get_email_url($email);
		$this->template->assign('email', $email);
		$this->template->assign('to_email_url', $to_email_url);
		$this->template->assign('title', '修改邮箱');
		$this->template->assign('url', '/user/send_new_email');
		$this->template->view('user/send_email_success.tpl');
	}

	/*public function save_new_email($code="")
	{
		if(empty($code))
		{
			show_404();
		}
		$result = $this->user_verify_service->check_email_verify_code($code,"",User_verify_service::PROCESS_MODIFY_EMAIL,TRUE,TRUE);
		if($result===false)
		{
			$data = array(
				'title' => '修改邮箱',
				'model' => 'user'
			);
			$this->smarty->view('user/tips.tpl',$data);
			return false;
		}
		else
		{
			$this->user_info_service->update_user_info($result['uid'],array("email"=>$result['receiver']));
			if($this->login_service->is_login())
			{
				$this->login_service->reload_user_info();
			}
			$data=array(
				"title"=>"邮箱修改成功",
				"type" =>"success",
				"msg" =>"你的新邮箱已经绑定成功",
				"url" =>"/user/user_info",
				"time"=>5
			);
			$this->smarty->view("common/message.tpl",$data);
		}
	}*/



}